package traffic

import (
	"time"
)

//
// FlowStatistics
// @Description:
//
type FlowStatistics struct {
	Name        string
	Flow        uint64
	FlowStamp   uint64
	FlowSpeed   uint64
	Packet      uint64
	PacketStamp uint64
	PacketSpeed uint64
}

//
// Init
// @Description:
// @receiver fp
//
func (fp *FlowStatistics) Init() {
	fp.Flow = 0
	fp.FlowStamp = 0
	fp.FlowSpeed = 0
	fp.Packet = 0
	fp.PacketStamp = 0
	fp.PacketSpeed = 0
	go fp.statistics()
}

//
// Process
// @Description:
// @receiver fp
// @param raw
// @return []byte
//
func (fp *FlowStatistics) Process(raw []byte) []byte {
	fp.Packet++
	fp.Flow += uint64(len(raw))
	return raw
}

//
// calcPacket
// @Description:
// @receiver fp
//
func (fp *FlowStatistics) calcPacket() {
	if fp.Packet == 0 {
		fp.PacketSpeed = 0
		return
	}
	fp.PacketSpeed = fp.Packet - fp.PacketStamp
	fp.PacketStamp = fp.Packet
}

//
// calcFlow
// @Description:
// @receiver fp
//
func (fp *FlowStatistics) calcFlow() {
	if fp.Flow == 0 {
		fp.FlowSpeed = 0
		return
	}
	fp.FlowSpeed = fp.Flow - fp.FlowStamp
	fp.FlowStamp = fp.Flow
}

//
// Statistics
// @Description:
// @receiver fp
//
func (fp *FlowStatistics) statistics() {
	for {
		time.Sleep(time.Second)
		fp.calcFlow()
		fp.calcPacket()
	}
}
